package core.commit;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import context.mm_constant;
import core.push.mm_push;
import core.reactor.mm_reactor;
import core.reactor.mm_start;
import log.mm_logger;
import utils.mm_parse;
import utils.mm_thread;

/**
 * 查询订单是否完成
 * @author dongyazhuo
 */
public class mm_query_order_complete {

	private String TAG = mm_query_order_complete.class.getSimpleName() + " : ";

	private mm_reactor _mm_reactor;

	public mm_query_order_complete(mm_reactor _mm_reactor) {
		super();
		this._mm_reactor = _mm_reactor;
		TAG += _mm_reactor._mm_config.getSet().getAccount_12306().getUser() + " : ";
	}

	/**
	 * 查询订单排队完成
	 */
	public void sendQueryOrderWaitTime() {
		int num = 1;
		while (true) {
			num++;
			if (num > mm_constant.OUT_NUM) {
				mm_logger.w(TAG + mm_constant.WAIT_OUT_NUM);
				Object order_id = queryMyOrderNoComplete();
				if (null != order_id) { // 排队失败，取消订单
					cancelNoCompleteMyOrder(order_id);
				}
				break;
			}

			Map<String, Object> url = _mm_reactor._mm_config.getUrl_config().get("queryOrderWaitTimeUrl");
			Map<String, Object> data_par = new HashMap<>();
			String req_url = String.format(url.get("req_url").toString(), System.currentTimeMillis());
			url.put("req_url", req_url);
			HashMap<String, Object> result = (HashMap<String, Object>) _mm_reactor._mm_http_client.send(url, data_par);
			if (null != result && mm_parse.parse_bool(result.get("status"))) {
				HashMap data = JSON.parseObject(result.get("data").toString(), HashMap.class);
				if (null != data.get("orderId")) {
					mm_logger.w(TAG + String.format(mm_constant.WAIT_ORDER_SUCCESS, data.get("orderId").toString()));
					mm_logger.w(TAG + String.format(mm_constant.WAIT_ORDER_SUCCESS, data.get("orderId").toString()));
					mm_logger.w(TAG + String.format(mm_constant.WAIT_ORDER_SUCCESS, data.get("orderId").toString()));
					new mm_push(data.get("orderId").toString(), _mm_reactor).push();
					mm_start.stop(_mm_reactor);
				} else if (null != data.get("msg")) {
					mm_logger.w(TAG + data.get("msg"));
					if (data.get("msg").toString().contains("今日将不能继续受理您的订票请求")) {
						mm_start.stop(_mm_reactor);
					}
					break;
				} else if (null != data.get("waitTime")) {
					mm_logger.w(TAG + String.format(mm_constant.WAIT_ORDER_CONTINUE, data.get("waitTime").toString()));
				}
			} else if (null != result.get("messages")) {
				mm_logger.w(TAG + String.format(mm_constant.WAIT_ORDER_FAIL, result.get("messages").toString()));
			} else {
				mm_logger.w(TAG + String.format(mm_constant.WAIT_ORDER_NUM, num + 1));
			}
			mm_thread.sleep(2000);
		}
		// reboot
		mm_logger.w(TAG + mm_constant.WAIT_ORDER_SUB_FAIL);
	}

	private void cancelNoCompleteMyOrder(Object order_id) {
		Map<String, Object> url = _mm_reactor._mm_config.getUrl_config().get("cancelNoCompleteMyOrder");
		Map<String, Object> data_par = new HashMap<>();
		data_par.put("sequence_no", order_id);
		data_par.put("cancel_flag", "cancel_order");
		data_par.put("_json_att", "");
		HashMap<String, Object> result = (HashMap<String, Object>) _mm_reactor._mm_http_client.send(url, data_par);
		if (null != result && null != result.get("data")) {
			HashMap data = JSON.parseObject(result.get("data").toString(), HashMap.class);
			String existError = mm_parse.parse_str(data.get("existError"));
			if ("N".equals(existError)) {
				mm_logger.i(TAG + mm_constant.CANCEL_ORDER_SUCCESS + order_id);
				mm_thread.sleep(2000);
				return;
			}
		}
		mm_logger.i(TAG + mm_constant.CANCEL_ORDER_FAIL + order_id);
	}

	/**
	 * 获取订单前需要进入订单列表页，获取订单列表页session
	 */
	private void initNoComplete() {
		Map<String, Object> url = _mm_reactor._mm_config.getUrl_config().get("initNoCompleteUrl");
		Map<String, Object> data_par = new HashMap<>();
		data_par.put("_json_att", "");
		_mm_reactor._mm_http_client.send(url, data_par);
	}

	/**
	 * 获取订单列表还在排队，排队返回true，错误返回false
	 * @return
	 */
	private Object queryMyOrderNoComplete() {
		// {httpstatus=200, validateMessages={},
		// data={"to_page":"cache","orderCacheDTO":{"array_passser_name_page":["王新莹"],"stationTrainCode":"G627","tickets":[{"passengerName":"王新莹","passengerIdTypeName":"中国居民身份证","ticketTypeName":"成人票","seatTypeCode":"O","seatTypeName":"二等座"}],"ticketCount":1,"fromStationName":"北京西","toStationCode":"ABV","message":{"code":"0","message":"对不起，由于您取消次数过多，今日将不能继续受理您的订票请求。1月26日您可继续使用订票功能。"},"startTimeString":"2019-02-13
		// 08:05","userId":1500003463156,"tourFlag":"dc","requestTime":"2019-01-25
		// 15:43:55","toStationName":"运城北","number":4,"queueName":"ORDER_P3","modifyTime":"2019-01-25
		// 15:43:56","requestId":6494469687952044020,"trainDate":"2019-02-13
		// 00:00:00","queueOffset":113669,"startTime":"1970-01-01
		// 08:05:00","fromStationCode":"BXP","waitCount":0,"waitTime":-2,"status":3}}, messages=[],
		// validateMessagesShowId=_validatorMessage, status=true}
		initNoComplete();
		Map<String, Object> url = _mm_reactor._mm_config.getUrl_config().get("queryMyOrderNoCompleteUrl");
		Map<String, Object> data_par = new HashMap<>();
		data_par.put("_json_att", "");
		HashMap<String, Object> result = (HashMap<String, Object>) _mm_reactor._mm_http_client.send(url, data_par);
		if (null != result && null != result.get("data")) {
			HashMap data = JSON.parseObject(result.get("data").toString(), HashMap.class);
			if (null != data.get("orderDBList")) {
				return result.get("data");
			}
			if (null != data.get("orderCacheDTO")) {
				HashMap orderCacheDTO = JSON.parseObject(data.get("orderCacheDTO").toString(), HashMap.class);
				HashMap message = JSON.parseObject(orderCacheDTO.get("message").toString(), HashMap.class);
				mm_logger.w(TAG + message.get("message"));
				if (message.get("message").toString().contains("今日将不能继续受理您的订票请求")) {
					mm_start.stop(_mm_reactor);
				}
				return null;
			}
		}
		return null;
	}
}
